
import { ref, reactive, computed, defineExpose, onMounted, onBeforeUnmount } from "vue";
import { ElMessage } from "element-plus";
import { emitter } from "@/utils/mitt";
export function usescreen() {
  // data
  const isdisabled = ref<boolean>(true);
  const MZData = [
    { "id": "3", "text": "性别" },
    { "id": "4", "text": "教育程度" },
    { "id": "5", "text": "收入来源" },
    { "id": "6", "text": "数额较大债务" },
    { "id": "7", "text": "投资知识" },
    { "id": "8", "text": "投资经验" },
    { "id": "9", "text": "产品偏好" },
    { "id": "10", "text": "投资期限" },
    { "id": "11", "text": "策略偏好" },
    { "id": "12", "text": "风险偏好" },
    { "id": "13", "text": "投资比例" },
    { "id": "14", "text": "用于投资的资产数额" },
    { "id": "15", "text": "年龄" },
  ]
  const TJData = [{ id: "1", text: ">" }, { id: "2", text: "=" }, { id: "3", text: "<" }, { id: "4", text: ">=" }, { id: "5", text: "<=" }, { id: "6", text: "≠" }]
  const BHData = [{ id: "1", text: "包含" }, { id: "2", text: "不包含" }];
  const CZData = [{ id: "4", text: "客户属性满足" }];
  const selData = {
    sexArr: [{ "id": "1", "text": "男" }, { "id": "2", "text": "女" }],
    study: [{ "id": "1", "text": "初等教育" }, { "id": "2", "text": "中等教育" }, { "id": "3", "text": "高等教育" }],
    income: [{ "id": "1", "text": "工资、劳务报酬" }, { "id": "2", "text": "生产经营所得" }, { "id": "3", "text": "利息、股息、转让证券等金融性资产收入" }, { "id": "4", "text": "出租、出售房地产等非金融性资产收入" }, { "id": "5", "text": "无固定收入" }],
    debt: [{ "id": "1", "text": "无" }, { "id": "2", "text": "住房抵押贷款等长期定额债务" }, { "id": "3", "text": "信用卡欠款、消费信贷等短期信用债务" }, { "id": "4", "text": "亲朋之间借款" }],
    Investment: [{ "id": "1", "text": "现在或此前曾从事金融、经济或财会等与金融产品投资相关的工作超过两年" }, { "id": "2", "text": "已取得金融、经济或财会等与金融产品投资相关专业学士以上学位" }, { "id": "3", "text": "取得证券从业资格、期货从业资格、注册会计师证书（CPA）或注册金融分析师证书（CFA）中的一项及以上" }, { "id": "4", "text": "无" }],
    experience: [{ "id": "1", "text": "有限" }, { "id": "2", "text": "一般 " }, { "id": "3", "text": "丰富" }, { "id": "4", "text": "非常丰富" }],
    preference: [{ "id": "1", "text": "银行存款" }, { "id": "2", "text": "债券、货币市场基金、债券型基金或其它固定收益类产品" }, { "id": "3", "text": "股票、混合型基金、偏股型基金、股票型基金等权益类投资品种" }, { "id": "4", "text": "期货、融资融券" }],
    horizon: [{ "id": "1", "text": "短期" }, { "id": "2", "text": "中期" }, { "id": "3", "text": "长期" }],
    tactics: [{ "id": "1", "text": "债券、货币市场基金、债券基金等固定收益类投资品种" }, { "id": "2", "text": "股票、混合型基金、偏股型基金、股票型基金等权益类投资品种" }, { "id": "3", "text": "期货、融资融券" }, { "id": "4", "text": "复杂或高风险金融产品" }, { "id": "5", "text": "其他产品" }],
    Risk: [{ "id": "1", "text": "盈亏10%以内" }, { "id": "2", "text": "盈亏10%-30%" }, { "id": "3", "text": "盈亏30%-50%" }, { "id": "4", "text": "盈亏超过50%" }],

  };
  const mType = [{ "id": "1", "text": "文本框" }, { "id": "2", "text": "大于、小于、等于" }, { "id": "3", "text": "包含、不包含" }];
  const endData = ref<any>([]);
  const myJSonar = ref<any>();

  // methods
  function selectFn(e: string | number, b: string | number, d: string | number) {
    // typ 2 = TJData ; typ 1 = CZData ; typ 3 = BHData ;
    var val = e;
    var typ = 1;
    var name = '';
    if (val == 3) {
      typ = 3;
      name = "sexArr"
    } else if (val == 4) {
      typ = 3;
      name = "study";
    } else if (val == 5) {
      typ = 3
      name = "income";
    } else if (val == 6) {
      typ = 3
      name = "debt";
    } else if (val == 7) {
      typ = 3
      name = "Investment";
    } else if (val == 8) {
      typ = 3
      name = "experience";
    } else if (val == 9) {
      typ = 3
      name = "preference";
    } else if (val == 10) {
      typ = 3
      name = "horizon"
    } else if (val == 11) {
      typ = 3
      name = "tactics"
    } else if (val == 12) {
      typ = 3
      name = "Risk"
    } else if (val == 13) {
      typ = 2
    } else if (val == 14) {
      typ = 2
    } else if (val == 15) {
      typ = 2
    } else {
      typ = null
    }

    endData.value[b].data[d].rather = '';
    endData.value[b].data[d].times = '';
    endData.value[b].data[d].rather2 = '';
    endData.value[b].data[d].times2 = '';
    endData.value[b].data[d].selectMore = '';
    endData.value[b].data[d].mType = typ;
    endData.value[b].data[d].mName = name;

  }

  function selectShow(e: any, b: string | number, d: string | number) {
    let isSelect = endData.value[b].data[d].isSelect;
    endData.value[b].data[d].isSelect = !isSelect
  }
  //活跃次数select下拉选择
  function selectFn2(e, b: string | number, d: string | number) {
    endData.value[b].data[d].selectMore = '';
    let selectd = endData.value[b].data[d].times;
    console.log("123", selectd)
    endData.value[b].data[d].selectMore = selectd;
    // endData.value[b].data[d].mVal += selectd
    // selectd.forEach((item, i) => {
    //   let dun = "";
    //   if (i) {
    //     dun = " | "
    //   }
    //   endData.value[b].data[d].selectMore += dun + item.text;
    //   endData.value[b].data[d].mVal += dun + item.id
    // })
    return false;
  }

  // type  点击按钮类型   { id: "1", text: "做过" }, { id: "2", text: "新增于" }, { id: "3", text: "活跃次数" }, { id: "4", text: "客户属性满足" }
  // id  并且对应的下标
  // ids 并且下面子类，或者对应的按钮
  function addItem(type: any, id: number, ids: any) {
    verifyNum();
    let obj = { type: type, term: '', rather: '', times: '', rather2: '', times2: '', selectMore: '', isSelect: '', mType: '', mName: '', mVal: '' };
    if (type == 2) {
      obj["term"] = 1;
    }
    if (type == 3) {
      //console.log(this.selectArrs.arr3);
      if (selectArrs.arr3.length >= 6) {
        return false;
      }
    }
    // 如果是非子类按钮点击时
    if (!ids && ids != 0) {
      id = id + 1;
    }

    if (endData.value[id]) {   //判断当前数组是否存在
      endData.value[id].data.push(obj)
    } else {
      endData.value.push({
        data: [obj]
      })
    }
  }

  /**
  * 移除
  * @param {number | string} id 当前点击数组对应的项的下标
  * @param {number | string} ids 当前点击数组对应的项子类那一项的下标
  */
  function removeItem(id: string | number, ids: any) {
    if (endData.value[id].data.length == 1) {  //如果是最后一条直接删除当前数组那一项
      endData.value.splice(id, 1);    //删除对应数据
    } else {
      //删除数组子类下的项
      endData.value[id].data.splice(ids, 1);    //删除对应数据
    }
  }

  //点击确定的事件
  function setChoose() {
    verifyNum();
    let arr = [];
    let isstate: number;
    const objData = JSON.parse(JSON.stringify(endData.value));
    objData.forEach((item: { data: any[]; }, index: number) => {
      let index2 = index + 1;
      item.data.forEach((a, i) => {
        let i2 = '';
        isstate = 1;
        if (i) i2 = i;
        isstate = VerifyContent(a)
        a["times"] = a["times"].toString();
        a["id"] = index2 + '' + i2;
        a.selectMore = a.selectMore == '' ? "" : a.selectMore.join(' | ')
        arr.push(a);
      });
    });
    let strArr = JSON.stringify(arr);

    if (strArr == "[]" || !isstate) { ElMessage.warning("请设置筛选条件！"); return; }
    emitter.emit("EmitCustomerGroup", arr);
  }

  function onCreate() {
    verifyNum();
    let arr = [];
    let isstate: number;
    const objData = JSON.parse(JSON.stringify(endData.value));
    objData.forEach((item, index) => {
      let index2 = index + 1;
      item.data.forEach((a, i) => {
        let i2 = '';
        isstate = 1;
        if (i) i2 = i;
        isstate = VerifyContent(a)
        a["times"] = a["times"].toString();
        a["id"] = index2 + '' + i2;
        a.selectMore = a.selectMore == '' ? '' : a.selectMore.join(' | ');
        a.mVal = a.selectMore;
        arr.push(a);
      });
    });
    let strArr = JSON.stringify(arr);
    if (strArr == "[]" || !isstate) { ElMessage.warning("请设置筛选条件！"); return; }
    myJSonar.value = strArr;//筛选条件
    emitter.emit("EM_openVisible", myJSonar);
  }


  function VerifyContent(a) {
    console.log("a", a)
    let isstate = 1;
    if (a.mType == '' && a.mName == '') isstate = 0;
    if (a.mType == 2 && a.mName == 'jypl') {
      if (a.daily === "") isstate = 0;
      if (a.rather === "") isstate = 0;
      if (a.times === "") isstate = 0;
    }

    if (a.mType == 2 && a.mName != 'jypl') {
      if (a.rather === "") isstate = 0;
      if (a.times === "") isstate = 0;
    }
    if (a.mType == 3) {
      if (a.rather === "") isstate = 0;
      if (a.selectMore === "" || a.selectMore?.length === 0) isstate = 0;
    }
    return isstate
  }


  emitter.on("clearChooses", () => {
    clearChoose()
  })
  function clearChoose() {
    endData.value = [];
    isdisabled.value = true;
    emitter.emit("clearChoose")
    // mini.get("UserGroup").setValue(0);
  }

  function verifyNum() {
    endData.value.forEach((item, index) => {
      item.data.forEach((a, i) => {
        if (Number(a.times)) {
          a.times = Number(a.times);
        } else {
          a.times = 0;
        }
        if (Number(a.times2)) {
          a.times2 = Number(a.times2);
        } else {
          a.times2 = 0;
        }
      });
    });
  }

  /**
   * 输入框对输入数字的处理
   * @param {obj} event js事件对象
   * @param {string|number} b 一级数组子类下标
   * @param {string|number} d 一级子类下的子类（二级下标）
   * @param {string} name 需要更改的字段name名
   * @param {string|number} type 需要处理的类型，type=1 正数和小数，type=2 正整数，type为空或其他 数字（包含小数、负数）
   * @param {number} max 输入框允许输入的最大值，这里默认是180
   * @returns
   */
  function changeNum(event, b, d, name, type, max = 180) {
    //响应鼠标事件，允许左右方向键移动
    event = window.event || event;
    if (event.keyCode == 37 || event.keyCode == 39) {
      return;
    }
    let val = event.target.value;
    let t = val.charAt(0);
    let t2 = val.charAt(1);
    if (type == 2) {
      val = val.replace(/^[^\d]+/g, ''); //非正整数都替换为空
      if (Number(val) > max) {
        val = max;
      }
    } else {
      //先把非数字的都替换掉，除了数字和.
      val = val.replace(/[^\d.]/g, "");
      //必须保证第一个为数字而不是.
      val = val.replace(/^\./g, "");
      //保证只有出现一个.而没有多个.
      val = val.replace(/\.{2,}/g, ".");
      //保证.只出现一次，而不能出现两次以上
      val = val.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
      //console.log(t);
      //console.log(t2);
      if (t == 0 && t2 == 0) {
        val = 0;
      }
      if (val.toString().length > 10) {
        val = Number(val).toFixed(8)
      }
      //console.log(val);
      if (Number(val) > max) {
        val = max;
      }
      if (type == 1) {

      } else {
        //如果第一位是负号，则允许添加   如果不允许添加负号 可以把这块注释掉
        if (t == '-') {
          val = '-' + val;
        }
      }

    }
    var linReg = /^[0]+$/gi;    //全部都为0
    var ax = endData.value[b].data[d]
    if (linReg.test(val)) {
      ax[name] = 0
    } else {
      ax[name] = val
    }
  }

  // 返显客户群条件
  emitter.on("ViewSecurities", (row) => {
    let endArry = [];
    isdisabled.value = false;
    row.forEach((item, index) => {
      let strId = item.id + "";
      let ids = strId.slice(0, 1) - 1;
      let times = item.times;
      if (times.indexOf(",") != -1) {
        times = times.split(",");
      }
      console.log("item", item)
      const obj = {
        "type": item.type,
        "term": item.term,
        "rather": item.rather,
        "times": times,
        "rather2": item.rather2,
        "times2": item.times2,
        "selectMore": item.selectMore == '' ? '' : item.selectMore.split(' | '),
        "isSelect": false,
        "mType": item.mType,
        "mName": item.mName,
        "mVal": item.mVal == '' ? '' : item.mVal.split(' | '),
      };
      if (endArry[ids]) {
        endArry[ids].data.push(obj)
      } else {
        endArry.push({
          data: [obj]
        })
      }

    });

    endData.value = endArry
  })

  function clearNoNum(obj) {
    if (!(/[^0]/gi.test(obj.value))) {
      return obj.value = 0;
    }
  }

  const selectArrs = computed(() => {
    let arr1 = [1], arr2 = [2], arr3 = [3], arr4 = [4];
    return { arr1, arr2, arr3, arr4 };
  });

  onBeforeUnmount(() => {
    emitter.off("clearChooses")
    emitter.off("ViewSecurities")
    emitter.off("EmitCustomerGroup");
    emitter.off("EM_openVisible");
  })

  return {
    MZData,
    TJData,
    BHData,
    CZData,
    selData,
    mType,
    endData,
    selectArrs,
    isdisabled,
    addItem,
    selectFn,
    selectFn2,
    selectShow,
    removeItem,
    setChoose,
    onCreate,
    clearChoose,
    clearNoNum,
    changeNum
  }
}
